#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <error.h>
#include<errno.h>
#define BUFFER_SIZE 255

int main(int argc, char *argv[])
{
	if(argc!=3){
		fprintf(stderr,"Usage: %s <server_address> <port>\n",argv[0]);
		return 1;
	}
	int client_sock;
	struct sockaddr_in server_addr;
	char send_msg[BUFFER_SIZE];
	char recv_msg[BUFFER_SIZE];
	int port;

	// 解析端口号
	port = atoi(argv[2]);
	if(port <=0 || port >65535){
		perror("port error");
		return 1;
	}
	/* 创建socket */
	client_sock = socket(AF_INET, SOCK_STREAM, 0);
	if (client_sock == -1){
		perror("socket error");
		return 1;
	}

	/* 指定服务器地址 */
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port); 
	if(inet_aton(argv[1], &server_addr.sin_addr) ==0){
		fprintf(stderr,"Invalid address/ Address not supported\n");
	} //127.0.0.1指向本机,argv[1]为ip地址
		memset(server_addr.sin_zero, 0, sizeof(server_addr.sin_zero)); //零填充

	/* 连接服务器 */
	if(connect(client_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1){
		perror("connect error");
		close(client_sock);
		return 1;
	}

	while(1){
		//读取用户输入的信息
	printf("Enter message to send: ");
	if(fgets(send_msg,BUFFER_SIZE,stdin) ==NULL){
		perror("error reading");
		close(client_sock);
		return 1;
	}
	size_t len =strlen(send_msg);
	if(len>0&&send_msg[len-1]=='\n'){
		send_msg[len -1]='\0';
	}

	if(strcmp(send_msg,"bye")==0){
		printf("exit\n");
		break;
	}
	/* 发送消息 */
	printf("Send: %s\n", send_msg);
	if(send(client_sock, send_msg, strlen(send_msg), 0) ==-1){
		perror("send error");
		break;
	}

	/* 接收并显示消息 */
	memset(recv_msg, 0, sizeof(recv_msg)); //接收数组置零
	if(recv(client_sock, recv_msg, sizeof(recv_msg), 0)==-1){
		perror("receive error");
		break;
	}
	if(strcmp(recv_msg,"bye")==0){
		printf("Server requested to exit.\n");
		break;
	}
	printf("Recv: %s\n", recv_msg);
	}
	

	/* 关闭socket */
	if(close(client_sock)==-1){
		perror("close error\n");
		return 1;
	}

	return 0;
}
